CODE 69. Minimum Path Sum

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/10/07/2013-10-07-CODE 69 Minimum Path Sum/

访问原文「CODE 69. Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public int minPathSum(int[][] grid) {
// Start typing your Java solution below
// DO NOT write main() function
int[][] sum = new int[grid.length][grid[0].length];
sum[0][0] = grid[0][0];
for (int i = 1; i < grid.length; i++) {
sum[i][0] = grid[i][0] + sum[i - 1][0];
}
for (int i = 1; i < grid[0].length; i++) {
sum[0][i] = grid[0][i] + sum[0][i - 1];
}
for (int i = 1; i < grid.length; i++) {
for (int j = 1; j < grid[0].length; j++) {
sum[i][j] = grid[i][j] + Math.min(sum[i - 1][j], sum[i][j - 1]);
}
}
return sum[sum.length - 1][sum[0].length - 1];
}
Jerky Lu wechat
欢迎加入微信公众号